<template>
  <div class="chatPage" @click="clickOutside($event)">
    <scroller-box
      id="scroll"
      ref="scroll"
      :dataList="Chat.chatList"
      :messageList="Chat.onmessageList"
      :pullDownRefresh="DOWN_CONFIG"
      :pullUpLoad="UP_CONFIG"
      :scrollToEndFlag="scrollToEndFlag"
      :beforePullUpWord="beforePullUpWord"
      @onPullUp="pullUpHandle"
      @onPullDown="pullDownHandle"
    >
      <div v-for="(item, index) in Chat.chatList" :key="item.FID" :data-FID="item.FID" :class="{myself:$store.state.userData.UserId == item.UserID }" :data-index="index" class="chat-square clearfix">
        <div class="head-portrait">
          <img :src="`${$store.state.baseURL}/api/Filse/GetPortrait?UserID=${item.UserID}`" />
        </div>
        <div class="chat-content">
          <div class="nickName">{{ item.FNickName }}</div>
          <span class="triangle"></span>
          <div :id="`cont${item.FID}`" class="chat-text clearfix" @touchstart="showDeleteButton(item, index, $event)" @touchend.prevent="cleartime(item, index)" v-html="item.FContent"></div>
          <div :class="{ show: showOption == index }" class="boxOption">
            <div class="shadeTip"><i></i></div>
            <a class="copyInfo" @click="handleCopy(item.FContent, $event)">复制</a>
            <a class="collecText" @click="InsCollection(item, index)">收藏</a>
            <a class="Contacthim" @click="callphone(item, index)">联系他</a>
          </div>
        </div>
      </div>
    </scroller-box>
  </div>
</template>

<script>
import $ from 'jquery'
import Chat from './client.js'
import { getExcludeHeight, DEVICE_RATIO, UP_CONFIG } from '@/until/until.js'
import clip from '@/until/clipboard.js'
import scrollerBox from '@/common/scroller/scroller.vue'

export default {
  components: {
    scrollerBox
  },
  data() {
    return {
      Chat: Chat,
      scrollToEndFlag: true,
      beforePullUpWord: '',
      onmessageList: '',
      DEVICE_RATIO,
      // DOWN_CONFIG,
      UP_CONFIG,
      DOWN_CONFIG: {
        threshold: -80 * DEVICE_RATIO,
        stop: 10 * DEVICE_RATIO
      },
      showOption: -1
    }
  },
  computed: {
    scrollElement() {
      return this.$refs.scroll
    },
    updateMessage() {
      return this.Chat.onmessageList
    }
  },
  watch: {
    updateMessage() {
      this.$nextTick(() => {
        if (this.updateMessage.length > 0) {
          const Jscroll = this.scrollElement.scroll
          this.updateMessageList(Jscroll, Jscroll.y)
        }
      })
    }
  },
  mounted() {
    Chat.init()
    this.$nextTick(() => {
      this.scrollingCal()
    })
  },
  destroyed() { // 离开当前页面后执行
    this.$store.commit('updateChatTime', '')
  },
  methods: {
    pullUpHandle(val) { // 向下加载
      // this.getContentData((res) => {
      //   this.scrollElement.PullingUpWord = '加载完成'
      //   setTimeout(() => {
      //     this.scrollElement.finish('PullUp')
      //     this.homeData = this.homeData.concat(res.object)
      //   }, 1000)
      // })
    },
    pullDownHandle(val) { // 向上刷新
      this.Chat.getNow(this.Chat.chatList[0].FAddTime) // 每次加载后更新时间
      this.Chat.getChatList((res) => {
        if (res.object.length > 0) {
          setTimeout(() => {
            this.scrollElement.finish('PullDown')
            this.Chat.chatList = res.object.concat(this.Chat.chatList)
            this.Chat.getNow(this.Chat.chatList[0].FAddTime)// 每次加载后更新时间
          }, 1000)
        } else {
          this.scrollElement.finish('PullDown')
          this.beforePullUpWord = '暂无更多数据'
        }
      })
    },
    scrollingCal() { // 滚动加载message 数据
      const Jscroll = this.scrollElement.scroll
      Jscroll.on('scroll', (res) => {
        this.updateMessageList(Jscroll, res.y)
      })
    },
    updateMessageList(Jscroll, y) {
      // 离底部只有1/6页面高度时，添加message到chatList
      if (Math.round(y - (Jscroll.wrapperHeight / '6')) <= Jscroll.maxScrollY || this.$store.state.mySend) {
        if (this.updateMessage && this.updateMessage.length > 0) {
          let Jmessage = []
          for (let item in this.updateMessage) {
            Jmessage.push(this.updateMessage[item])
          }
          this.Chat.chatList = this.Chat.chatList.concat(Jmessage)
          this.Chat.onmessageList = []
        }
      }
    },
    showDeleteButton(item, index, event) {
      const This = this
      clearInterval(this.Loop) // 再次清空定时器，防止重复注册定时器
      this.Loop = setTimeout(() => {
        this.showOption = index
      }, 1000)
    },
    cleartime(id, course_id) {
      // 这个方法主要是用来将每次手指移出之后将计时器清零
      clearInterval(this.Loop)
    },
    handleCopy(content, event) { // 点击复制
      content = content.replace(/<(?!br).*?>/g, '').replace(/<br>/g, ' \n')
      clip(content, event)
    },
    InsCollection(item, index) {
      const getPage = { FChatID: item.FID }
      this.$axios.get('/api/Collections/InsCollection', getPage)
        .then((response) => {
          const res = response.data
          if (res.code == 1) {
            this.$message({
              message: '收藏成功',
              type: 'success'
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    callphone(item, index) {
      if (window.webkit || window.androidCall) {
        if (this.$store.state.customerPort == 'Android') {
          window.androidCall.call(item.FTelLink.toString())
        } else if (this.$store.state.customerPort == 'iPhone') {
          window.webkit.messageHandlers.makePhoneCall.postMessage(item.FTelLink.toString())
        } else {
          return false
        }
      }
    },
    clickOutside(event) {
      if (!$(event.target).hasClass('chat-text') && !$(event.target).hasClass('boxOption')) {
        this.showOption = -1
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
